/**
 * Created by kaki on 2017/4/6.
 */
import axios from 'axios'
import bus from '../bus'
import { apiUrl, baseUrl } from '../config'

export const http = axios.create({
  baseURL: apiUrl
})

const ua = navigator.userAgent

http.interceptors.request.use(
  (config) => {
    bus.$emit('toggleLoading', true)
    if (window.localStorage.getItem('accessToken')) {
      config.headers.common['Authorization'] = 'Bearer ' + window.localStorage.getItem('accessToken')
    }
    return config
  },
  (error) => {
    if (error) {
      window.localStorage.removeItem('accessToken')
      window.localStorage.removeItem('user')
      if ((/MicroMessenger/i).test(ua)) {
        window.location.href = apiUrl + '/oauth/redirect/weixin?role=guest&authUrl=' + baseUrl + '/code' + '&redirectUrl=' + window.location.href
      } else {
        window.location.href = apiUrl + '/oauth/redirect/weixinweb?role=guest&redirectUrl=' + window.location.href
      }
    }
    return error
  }
)

http.interceptors.response.use(
  (response) => {
    bus.$emit('toggleLoading', false)
    bus.$emit('isAppShow', false)
    return response
  },
  (error) => {
    const { response } = error
    bus.$emit('toggleLoading', false)
    // Something happened in setting up the request that triggered an Error
    if (!response) {
      window.swal('error', '网络错误', 'error')
      return Promise.reject(error)
    }

    /**
     * If token is either expired, not provided or invalid
     * then redirect to login. On server side the error
     * messages can be changed on app/Providers/EventServiceProvider.php
     */

    if (response.status === 401) {
      window.localStorage.removeItem('accessToken')
      window.localStorage.removeItem('user')
      if ((/MicroMessenger/i).test(ua)) {
        window.location.href = apiUrl + '/oauth/redirect/weixin?role=guest&authUrl=' + baseUrl + '/code' + '&redirectUrl=' + encodeURIComponent(window.location.href)
      } else {
        window.location.href = apiUrl + '/oauth/redirect/weixinweb?role=guest&redirectUrl=' + encodeURIComponent(window.location.href)
      }
      return false
    }
    if (response.status === 422) {
      window.swal('error', response.data.message, 'error')
    }
    if (response.status === 404) {
      bus.$emit('isAppShow', true)
      window.swal('抱歉', '活动已过期', 'error')
    }

    /**
     * Error messages are sent in arrays
     */
    return Promise.reject(error)
  },

)

const getData = obj => obj.data
// 当前用户
export const requestMe = (config = {}) => {
  let userInfo = window.localStorage.getItem('user')
  if (userInfo) {
    return new Promise((resolve, reject) => {
      resolve(JSON.parse(userInfo))
    })
  }
  return http.get(`/api/user/me`, config).then(getData).then(
    (resp) => {
      if (resp && resp.data) {
        let userInfo = resp.data
        window.localStorage.setItem('user', JSON.stringify(userInfo))
        return userInfo
      }
    }
  )
}
// 推广者-列表页
export const requestStore = (config = {}) => { return http.get(`/api/activity/sponsors`, config) }
// 推广者-活动页
export const requestStoreId = (sponsorsId, config = {}) => { return http.get(`/api/activity/sponsors/${sponsorsId}`, config).then(getData) }
// 用户详情页
export const requestDetail = (sponsorsId, detailId, config = {}) => { return http.get(`/api/activities/sponsors/${sponsorsId}/details/${detailId}`, config).then(getData) }
// 发表评价
export const requestEvaluate = (detailId, config = {}) => { return http.post(`/api/activity/sponsor/details/${detailId}/comments`, config) }
// 报名
export const requestSign = params => { return http.post(`/api/activity/sponsor/details`, params).then(getData) }
// 短信验证码
export const requestCode = params => { return http.post(`/api/auth/sms/code`, params).then(getData) }
// 手机验证
export const requestPhone = params => { return http.post(`/api/user/bind/phone`, params).then(getData) }
// 点赞
export const requestLike = (detailId, config = {}) => { return http.get(`/api/activity/sponsor/details/${detailId}/like`, config) }
// 支持者
export const requestPayments = (detailId, config = {}) => { return http.get(`api/activity/sponsor/details/${detailId}/payments`, config) }
// 微信分享
export const requestJssdk = (detailId, config = {}) => { return http.get(`/api/wechat/jssdk?url=` + encodeURIComponent(window.location.href), config) }
// 支付
export const requestPayment = (detailId, params) => { return http.post(`/api/activity/sponsor/details/${detailId}/payments`, params).then(getData) }
